#include "webpage.h"
#include "BleManager.h"
#include "HIDPS2conv.h"
#include <WebServer.h>

extern WebServer server;
extern void BLE_remove(String address);
extern void BLE_pair(String address);
extern void BLE_scan();

HIDPS2conv_HIDPoint *getDevices() {
    return HIDPS2conv::s_hidPoint;
}

BleServerConnector *getBLEAdvertisedDevices() {
    return BleManager::s_bleConnectors;
}

// 主页
void handleRoot() {
    static const String html = "\
<html>\
<head>\
  <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>\
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>\
  <link rel='stylesheet' href='common.css'>\
  <title>蓝牙/USB键鼠适配器(PS/2)</title>\
</head>\
<body>\
  <div class='header'>蓝牙/USB键鼠适配器(PS/2)</div>\
  <div class='content'>\
      <div style='width:100%; height: 20px;'></div>\
      <div class='bigButton-container'>\
        <button class='bigButton' onclick='window.location.href=\"devices\"'>设备</button>\
        <button class='bigButton' onclick='window.location.href=\"macro\"'>宏</button>\
      </div>\
  </div>\
</body>\
</html>";
    server.send(200, "text/html", html);
}

// 设备管理页面
void handleDevices() {

    String removeAddress = server.arg("remove");
    String pairAddress = server.arg("pair");
    String doScan = server.arg("scan");
    if (removeAddress.length()) {
        BLE_remove(removeAddress);
        server.sendHeader("Location", "/devices"); // 目标URL
        server.send(303, "text/plain", "Redirecting to /devices...");
        return;
    } else if (pairAddress.length()) {
        BLE_pair(pairAddress);
        server.sendHeader("Location", "/devices"); // 目标URL
        server.send(303, "text/plain", "Redirecting to /devices...");
        return;
    } else if (doScan.length()) {
        BLE_scan();
        server.sendHeader("Location", "/devices"); // 目标URL
        server.send(303, "text/plain", "Redirecting to /devices...");
    }

    HIDPS2conv_HIDPoint *hidDevices = getDevices();
    BleServerConnector *advertisedDevices = getBLEAdvertisedDevices();

    int maxLen = 1000;
    char temp[maxLen];
    char statusName[13] = {0};
    char deviceType[28] = {0};
    char deviceName[33] = {0};
    char deviceAddress[18] = {0};
    String htmlList1 = "";
    for (int i = 0; i < 5; i++) {
        HIDPS2conv_HIDPoint &hidDevice = hidDevices[i];

        if (hidDevice.type == 1) {
            if (hidDevice.pBleServerConnector->_type == 1) {
                sprintf(deviceType, "蓝牙键盘（%s）", hidDevice.pBleServerConnector->_keyboard_mode == 0 ? "美式" : "日式");
            } else {
                strcpy(deviceType, "蓝牙鼠标");
            }
            strcpy(deviceName, hidDevice.pBleServerConnector->_name);
            strcpy(deviceAddress, hidDevice.pBleServerConnector->_address);
            switch (hidDevice.pBleServerConnector->_status) {
            case -1:
                strcpy(statusName, "连接失败");
                break;
            case 0:
                strcpy(statusName, "未连接");
                break;
            case 1:
            case 2:
                strcpy(statusName, "连接中");
                break;
            case 3:
                strcpy(statusName, "已连接");
                break;
            default:
                statusName[0] = 0;
                break;
            }
            snprintf(temp, maxLen,
                     "\
<tr>\
<td><div class='item-title'>%s</div><div class='item-description'>%s</div></td>\
<td width='50px'>%s</td>\
<td width='58px'><button class='normalButton' onclick='window.location.href=\"devices?remove=%s\"'>删除</button></td>\
</tr>",
                     deviceType,
                     deviceName,
                     statusName,
                     deviceAddress);
        } else if (hidDevice.type == 2) {
            if (hidDevice.pUSBClientConnector->_type == 1) {
                sprintf(deviceType, "USB键盘（%s）", hidDevice.pUSBClientConnector->_keyboard_mode == 0 ? "美式" : "日式");
            } else {
                strcpy(deviceType, "USB鼠标");
            }
            sprintf(deviceName, "%02x%02x%02x%02x",              // 设备标识
                    hidDevice.pUSBClientConnector->_DeviceID[0], //
                    hidDevice.pUSBClientConnector->_DeviceID[1], //
                    hidDevice.pUSBClientConnector->_DeviceID[2], //
                    hidDevice.pUSBClientConnector->_DeviceID[3]);

            snprintf(temp, maxLen,
                     "\
<tr>\
<td><div class='item-title'>%s</div><div class='item-description'>%s</div></td>\
<td width='50px'>USB#%d</td>\
<td width='58px'></td>\
</tr>",
                     deviceType,
                     deviceName,
                     hidDevice.pUSBClientConnector->usbNum);
        } else {
            continue;
        }

        htmlList1 += temp;
    }

    String htmlList2 = "";
    for (int i = 0; i < 10; i++) {
        BleServerConnector &advertisedDevice = advertisedDevices[i];
        if (advertisedDevice.isEmpty() || advertisedDevice._fixed) {
            // 跳过空的，或已配对的
            continue;
        }
        snprintf(temp, maxLen,
                 "\
<tr>\
  <td><div class='item-title'>%s</div><div class='item-description'>%s</div></td>\
  <td width='58px'><button class='normalButton' onclick='window.location.href=\"devices?pair=%s\"'>配对</button></td>\
</tr>",
                 advertisedDevice._type == 1 ? "蓝牙键盘" : "蓝牙鼠标",
                 advertisedDevice._name,                 
                 advertisedDevice._address);

        htmlList2 += temp;
    }
    String html = "\
<html>\
<head>\
  <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>\
  <meta http-equiv='refresh' content='3'>\
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>\
  <link rel='stylesheet' href='common.css'>\
  <title>设备</title>\
</head>\
<body>\
  <div class='header'><a href='/' class='header-link'>蓝牙/USB键鼠适配器(PS/2)</a></div>\
  <div class='content'>\
    <div class='title1'>设备</div>\
    <div class='header2'>\
      <div class='title2'>可用设备</div>\
      <span class='notification-text'></span>\
    </div>\
    <table class='list-table'>\
      <tbody>" + htmlList1 +
                  "\
      </tbody>\
    </table>\
    <div class='header2'>\
      <div class='title2'>周围蓝牙设备&nbsp;&nbsp;&nbsp;&nbsp;</div>\
      <button class='normalButton' onclick='window.location.href=\"devices?scan=1\"'>搜索</button>\
      <span class='notification-text'></span>\
    </div>\
    <table class='list-table'>\
      <tbody>" + htmlList2 +
                  "\
      </tbody>\
    </table>\
</body>\
</html>";
    server.send(200, "text/html", html);
}

void handleCSS() {
    static const String html = "\
        body {\
          font-family: Arial, sans-serif;\
          margin: 0;\
          display: flex;\
          flex-direction: column;\
          align-items: center;\
          min-height: 100vh;\
          background-color:rgb(208, 232, 255);\
        }\
        \
        .content {\
          padding: 20px;\
          width: 90%;\
          /* max-width: 800px; /* 进一步增大容器宽度以适应大按钮 */\
        }\
        \
        .bigButton-container {\
          display: grid;\
          grid-template-columns: repeat(2, 1fr);\
          gap: 40px; /* 增大按钮间距 */\
          width: 100%;\
        }\
        \
        .bigButton {\
          aspect-ratio: 1/1;\
          display: flex;\
          align-items: center;\
          justify-content: center;\
          background-color: #66b3ff;\
          color: white;\
          border: none;\
          border-radius: 20px; /* 增大圆角 */\
          font-size: 2rem; /* 超大按钮文字 */\
          font-weight: bold; /* 加粗文字 */\
          cursor: pointer;\
          padding: 10px; /* 增大内边距 */\
          text-align: center;\
          box-shadow: 0 8px 16px rgba(0,0,0,0.3); /* 更明显的阴影 */\
          transition: all 0.3s;\
          min-height: 100px; /* 确保按钮足够大 */\
        }\
        \
        .bigButton:hover {\
          /* background-color: #4da6ff;/* */\
          /* transform: scale(1.05);  /* */\
        }\
        .normalButton {\
          background-color: #66b3ff;\
          color: white;\
          border: none;\
          border-radius: 5px;\
          padding: 4px 12px;\
          font-size: 1rem;\
          cursor: pointer;\
          transition: all 0.3s;\
          box-shadow: 0 4px 8px rgba(0,0,0,0.3); /* 更明显的阴影 */\
        }\
        \
        .normalButton:hover {\
          /* background-color: #4da6ff;/* */\
          /* transform: scale(1.05); /* */\
        }\
        \
        .bigButton-text {\
          display: flex;\
          flex-direction: column;\
          line-height: 1.2; /* 调整行高 */\
        }\
        \
        .list-table {\
          width: 100%;\
          border-collapse: separate; /* 关键：分离边框模式才能显示圆角 */ \
          border-spacing: 0;\
          margin: 20px auto;\
          background: white;\
          border-radius: 10px;\
        }\
        \
        .list-table th {\
          background-color: #f2f2f2;\
          padding: 4px 4px;\
          text-align: middle;\
          border-bottom: 2px solid #ddd;\
          font-size: 1rem;\
        }\
        \
        .list-table td {\
          padding: 8px 8px;\
          border-bottom: 1px solid #ddd;\
          vertical-align: left;\
          font-size: 1rem;\
          line-height: 1.2; /* 调整行高 */\
        }\
        \
        .list-table tr:hover {\
          /* background-color: #f5f5f5; /* */\
        }\
        .header-link,\
        .header-link:visited { /* 添加:visited伪类 */\
            color: white; /* 正常状态和访问后都保持白色 */\
            text-decoration: none;\
        }\
        \
        .header {\
          display: flex;\
          height: 50px;\
          width: 100%;\
          color: white;\
          background-color: #2196F3; /* 蓝色背景 */\
          font-size: 1.4rem;\
          font-weight: bold;\
          align-items: center;\
          margin-bottom: 5px;\
          padding-left: 40px;\
        }\
        .header2 {\
          display: flex;\
          align-items: center;\
          gap: 10px;  /* 控制标题、按钮、通知之间的间距 */\
          margin-bottom: 5px;\
        }\
        \
        .title1 {\
          font-size: 1.2rem;\
          font-weight: bold;\
          margin-left: 5px;\
        }\
        .title2 {\
          font-size: 1rem;\
          margin-left: 10px;\
          color:rgb(133, 131, 131);\
        }\
        .notification-text {\
          color: red;\
          margin-left: 10px;  /* 仅让通知和按钮之间有点间距 */\
        }\
        \
        .item-title {\
          font-size: 1tem;\
          margin: 0;\
        }\
        \
        .item-description {\
          font-size: 0.8rem;\
          color: #999;\
          margin: 5px 0 0 0;\
        }\
        ";
    server.send(200, "text/plain; charset=utf-8", html);
}

void handleJS() {
    static const String html = "";

    server.send(200, "text/html", html);
}

//
void handleNotFound() {
    String message = "File Not Found\n\n";
    message += "URI: ";
    message += server.uri();
    message += "\nMethod: ";
    message += (server.method() == HTTP_GET) ? "GET" : "POST";
    message += "\nArguments: ";
    message += server.args();
    message += "\n";

    for (uint8_t i = 0; i < server.args(); i++) {
        message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
    }

    server.send(404, "text/plain", message);
}
